package com.example.appinting.SQL;

import android.os.StrictMode;
import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MysqlHelper {
    /***
     * 数据库驱动
     */
    private static String driver="com.mysql.jdbc.Driver";
    /**
     * 数据库路径
     *
     */
    private static String url="jdbc:mysql://10.0.2.2:3306/hospital_system?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
    /**
     * 用户名
     */
    private static String user="root";
    /**
     * 密码
     */
    private static String password="123456";

    /**
     * 加载驱动类(只需要加载一次) static{} -- 静态块
     *
     *
     */
    static{
        try {
            Class.forName(driver);
            Log.i("TAG", "加载驱动成功: ");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 打开连接  抛出异常 交给调用者处理
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Connection	conn= null;
        Log.i("url", url);
        conn=DriverManager.getConnection(url, user, password);
        Log.i("TAG", "数据库链接成功: ");
        return conn;
    }
    /**
     * 关闭数据库资源从小到大
     * @param conn
     * @param ps
     * @param rs
     */
    public void  closeAll(Connection conn, PreparedStatement ps,ResultSet rs) {
        try {
            if (rs!=null) {
                rs.close();
            }if (ps!=null) {
                ps.close();

            }if (conn!=null) {
                conn.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }
    public int myExecutteUpdate(String sql,Object...pars){
        int result =0;
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            conn=getConnection();
            ps=conn.prepareStatement(sql);
            if (pars!=null&& pars.length!=0) {
                for (int i = 0; i < pars.length; i++) {
                    ps.setObject(i+1, pars[i]);
                }
            }
            result =ps.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            closeAll(conn, ps, rs);
        }
        return result;




    }
}